package com.jflm.util;



import java.io.*;
import java.security.*;
import java.security.cert.*;
import java.security.spec.*;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author unascribed
 * @version 1.0
 */

public class SignUtil {
  public static PrivateKey genPrivateKey(byte[] key) {
    //get the private key
    PrivateKey pk = null;
    try{
      PKCS8EncodedKeySpec peks = new PKCS8EncodedKeySpec(key);
      KeyFactory kf = KeyFactory.getInstance("RSA");
      pk = kf.generatePrivate(peks);
    } catch(Exception e) {
      return null;
    }
    return pk;
  }
  public static byte[] sign(PrivateKey pk, byte[] data) {
    //get the signature
    byte[] sb = null;
    try{
      Signature sig = Signature.getInstance("SHA1withRSA");
      sig.initSign(pk);
      sig.update(data);
      sb = sig.sign();
    } catch(Exception e) {
      return null;
    }
    return sb;
  }
  public static X509Certificate genCertificate(byte[] certData) {
    //load the cert
    ByteArrayInputStream bais = new ByteArrayInputStream(certData);
    X509Certificate cert = null;
    try{
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      cert = (X509Certificate)cf.generateCertificate(bais);
    } catch(Exception e) {
      return null;
    }
    return cert;
  }
  public static boolean verify(X509Certificate cert, byte[] plain, byte[] signData) {
    try{
      Signature sig = Signature.getInstance("SHA1withRSA");
      sig.initVerify(cert);
      sig.update(plain);
      return sig.verify(signData);
    } catch(Exception e) {
      return false;
    }
  }
}